from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import login_required
from models import ActionCategory, Project

import utils
import os
import logging
import traceback

list_links = """
<a href="/actions">Next Actions</a> | 
<a href="/projects">Projects</a> | 
<a href="/someday-maybe">Someday/Maybe</a> |
<a href="/settings">Settings</a>
"""

header = """
<span class="title">Getting Things Done</span> <span class="hint">%s (<a href="%s">logout</a>)</span> <br /><br />
""" + list_links + """
<hr />
"""

footer = """
<hr />
""" + list_links

def template_default_values():
  return  {
    'header': header % (users.get_current_user(), users.create_logout_url(users.create_login_url("/"))),
    'footer': footer,
    'title': '<TITLE>Getting Things Done</TITLE>'
  }

def verify_logged_in(request_handler):
  if not users.get_current_user():
    url = users.create_login_url(request_handler.request.uri)
    request_handler.redirect(url)

    
class SomedayMaybePage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'projects': utils.someday_maybe_ideas()}
    template_values.update(template_default_values())
    path = os.path.join(os.path.dirname(__file__), 'someday_maybe.html')
    self.response.out.write(template.render(path, template_values))
    

class ProjectDetailPage(webapp.RequestHandler):
  @login_required
  def get(self):
    key = self.request.get('project')
    logging.info("Searching for any project by key '%s'" % key)
    try:
      project = Project.get(key)
      template_values = {'project': project}
      template_values.update(template_default_values())
      path = os.path.join(os.path.dirname(__file__), 'project_detail.html')
      content = template.render(path, template_values)
    except BaseException, e:
      content = "Sorry! Unable to show project detail for project key '%s': %s." % (key, e)
    self.response.out.write(content)


class ProjectPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'projects': utils.projects()}
    template_values.update(template_default_values())
    path = os.path.join(os.path.dirname(__file__), 'project.html')
    self.response.out.write(template.render(path, template_values))


class CompletedProjectPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'completed_projects': utils.completed_projects()}
    template_values.update(template_default_values())
    path = os.path.join(os.path.dirname(__file__), 'completed_project.html')
    self.response.out.write(template.render(path, template_values))


class ActionPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'categories': utils.categories()}
    template_values.update(template_default_values())
    path = os.path.join(os.path.dirname(__file__), 'action.html')
    self.response.out.write(template.render(path, template_values))
    

class CategoryPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'categories': utils.categories()}
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'category.html')
    self.response.out.write(template.render(path, template_values))
    
    
class CompletedActionPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'completed_actions': utils.completed_actions()}    
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'completed.html')
    self.response.out.write(template.render(path, template_values))
    
    
class OpenTaskPage(webapp.RequestHandler):
  @login_required
  def get(self):
    template_values = {'tasks': utils.open_tasks()}    
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'task.html')
    self.response.out.write(template.render(path, template_values))


class SendEmailPage(webapp.RequestHandler):
  @login_required
  def get(self):
    email = utils.get_config_value('mru_email')
    cat = utils.get_config_value('mru_cat_email')
    logging.info('mru cat: %s' % cat)
    template_values = {
      'categories': utils.categories(), 
      'mru_email': email if email else utils.cuser().email(),
      'mru_cat': cat if cat else utils.categories().get()}
    logging.info('template values: %s' % template_values)
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'send_email.html')
    self.response.out.write(template.render(path, template_values))    


class EmailResultPage(webapp.RequestHandler):
  def post(self):
    # send the email
    success = True
    try:
      category = self.request.get('category')
      to_address = self.request.get('email')
      subject = category
      body = "HTML body contains Next Actions"
      template_values = {'actions': utils.actions_by_category(category)}    
      path = os.path.join(os.path.dirname(__file__), 'action_email.html')
      html_body = template.render(path, template_values)
      logging.info('html body: %s' % html_body)
      mail.send_mail(utils.cuser().email(), to_address, subject, body, html=html_body)
    except BaseException, e:
      logging.error(e)
      logging.error(traceback.format_exc())
      success = False

    # mark the email address,category that was used
    utils.set_config('mru_email', to_address)
    utils.set_config('mru_cat_email', category)

    # present the results page
    template_values = {'success': success, 'email': to_address}
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'email_result.html')
    self.response.out.write(template.render(path, template_values))    


class SettingPage(webapp.RequestHandler):
  @login_required
  def get(self):
    settings = utils.settings()
    template_values = {'settings': settings}
    template_values.update(template_default_values())    path = os.path.join(os.path.dirname(__file__), 'settings.html')
    self.response.out.write(template.render(path, template_values))    


class CategoryProcessor(webapp.RequestHandler):
  def post(self):
    verify_logged_in(self)
    do = self.request.get('do')
    if do == 'create':
      cat = ActionCategory()
      cat.user = utils.cuser()
      cat.name = self.request.get('name')
      cat.description = self.request.get('description')
      cat.put()
    elif do == 'delete':
      cat = db.get(self.request.get('key'))
      cat.delete()
      
    self.redirect('/categorypage')
